package com.lvyq.myplayer.ui.fragment

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.lvyq.myplayer.R
import com.lvyq.myplayer.adapter.singer.SingerAdapter
import com.lvyq.myplayer.model.singer.SingerInfoModel
import com.lvyq.myplayer.parcelable.SingerInfoData
import com.lvyq.myplayer.ui.activity.singer.SingerIndexActivity

/**
 * 歌手列表页
 */
class SingerListFragment : Fragment() {
    private lateinit var adapter: SingerAdapter
    private var letter = "热"
    private var singerType = -1
    private var sexType = -1

    private lateinit var recyclerView:RecyclerView

    lateinit var viewSingerModel: SingerInfoModel
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        val view = inflater.inflate(R.layout.fragment_singer_list, container, false)
        recyclerView = view.findViewById(R.id.singerGrid)

        // 设置网格布局
        recyclerView.layoutManager = GridLayoutManager(context, 4)
        adapter = SingerAdapter(ArrayList(), object : SingerAdapter.OnItemClickListener {
            override fun onItemClick(position: Int, data: SingerInfoData) {
                var intent = Intent(context, SingerIndexActivity::class.java)
                intent.putExtra("singerInfo",data)
                startActivity(intent)
            }
        })
        recyclerView.adapter = adapter

        // 从 arguments 获取当前字母
        arguments?.let {
            letter = it.getString("LETTER", "热") ?: "热"
            singerType = it.getInt("SINGER_TYPE", -1)
            sexType = it.getInt("SEX_TYPE", -1)

        }

        initData()

        return view
    }


    // 新增参数更新方法
    fun updateFilters(newSingerType: Int?, newSexType: Int?) {
        newSingerType?.let { singerType = it }
        newSexType?.let { sexType = it }

        // 立即刷新数据（无论Fragment是否可见）
        if (isAdded && !isDetached && view != null) {
            viewSingerModel.getSingerLst(letter, singerType, sexType)
        }

    }


    private fun initData() {
        if (!::viewSingerModel.isInitialized) {
            viewSingerModel = ViewModelProvider(this)[SingerInfoModel::class.java]
        }

        viewSingerModel.data.observe(viewLifecycleOwner) { data ->
            adapter.updateData(ArrayList(data.data))
        }

        // 初始加载（使用当前过滤条件）
        viewSingerModel.getSingerLst(letter, singerType, sexType)
    }

    override fun onDestroyView() {
        // 清理资源防止内存泄漏
        viewSingerModel.data.removeObservers(viewLifecycleOwner)
        super.onDestroyView()
    }



}